import { get, query, request as Request } from ".";
//localStorage save jwt
const JWT = "JWT";
const USER_INFO = "USER_INFO";
export interface AuthInfo {
  _id: string;
  username: string;
  role: number;
  mail?: string;
  lastUpdate: string;
}
export interface UpdateAuthBack {
  message: string;
  jwt: string;
  newUser: AuthInfo;
}

//# 所有涉及到设置/获取localStorage变量的操作统一管理
const setLocalJWT = (jwt: string) => {
  localStorage.setItem(JWT, jwt);
};

export const getLocalJWT = () => localStorage.getItem(JWT);
export const clearLocalJWT = () => localStorage.removeItem(JWT);

export const setLocalUser_Info = (userInfo: AuthInfo) => {
  localStorage.setItem(USER_INFO, JSON.stringify(userInfo));
};

export const getLocalUser_Info = () => localStorage.getItem(USER_INFO);
export const clearLocalUser_Info = () => localStorage.removeItem(USER_INFO);

export const checkUsernameValid = async (username: string) => {
  const { data } = await get("/checkUsernameValid", { params: { username } });
  return data;
};

export const getAuthByToken = async (): Promise<{
  status: boolean;
  user?: AuthInfo;
  message: string;
} | void> => {
  const jwt = getLocalJWT();
  if (!jwt) return;
  const { data } = await query("/getUserByToken", { params: { jwt } });
  return data;
};

export interface AuthProps {
  username: string;
  password: string;
}

interface IRequest {
  <T>(url: string): (params: T) => Promise<UpdateAuthBack | void>;
}

const request: IRequest = url => async params => {
  const { data } = await Request(url, params);
  if (data) {
    console.log(`${url}result`, data);
    setLocalJWT(data.jwt);
    setLocalUser_Info(data.user);
    return data;
  }
};

export const login = request<AuthProps>("/login");

export const register = request<AuthProps>("/register");

interface IUpdateUsername {
  newUsername: string;
  password: string;
}

export const updateUsername = request<IUpdateUsername>("/updateUsername");

interface IUpdatePassword {
  password: string;
  newPassword: string;
}

export const updatePassword = request<IUpdatePassword>("/updatePassword");

export const sendMailCode = async (mail: string): Promise<string | void> => {
  const { data } = await Request("/sendMailCode", { mail });
  return data;
};

interface IVerificationMailCode {
  code: string;
  encryptedInfo: string;
}

export const verificationMailCode = request<IVerificationMailCode>(
  "/verificationMailCode"
);
